import axios from 'axios';
import qs from 'qs';
import md5 from 'js-md5';
import { VariableType } from '../utils/variable-type';
import { getCookie } from './common.js';
//公用url地址前缀
// const public_url = 'https://xcx.39yu.cn/client/h5/';
const public_url = 'https://www.manydoctor.com/client/h5/';
// const public_url = 'http://192.168.0.168/client/h5/';
//加密密鈅token
const secret_key = 'ca72a0b32dd624014e49805c9f51fa4e';

export default class {
    // baseURL = 'https://xcx.39yu.cn/client/h5/';
    baseURL = 'https://www.manydoctor.com/client/h5/';

    timeout = 8000;
    clientId = 'lopsa2viq888cw80';
    secretKey = 'ca72a0b32dd624014e49805c9f51fa4e';

    constructor() {
        axios.defaults.baseURL = this.baseURL;
        axios.defaults.timeout = this.timeout;
    }
    /**
     * get请求
     * @param {string} url 请求地址
     * @param {string} data 加密字段
     * @param {string} noEncryption 非加密字段
     */
    get(url, data={}, noEncryption={}) {
        this._readData(url, data, noEncryption);
        let params = this._secretToken(data);
        let datas = Object.assign({}, params, noEncryption);
        axios.defaults.headers = this._headers();
        // return axios.get(url, {params: datas});
        return new Promise((resolve,reject)=>{
            axios.get(url, {params: datas}).then((res)=>{
                if(res.data.status == 1){
                    resolve(res.data);
                }else if(res.data.status == 2){
                    alert(res.data.message);
                }
            })
        })
    }
    /**
     * post请求
     * @param {string} url 请求地址
     * @param {string} data 加密字段
     * @param {string} noEncryption 非加密字段
     */
    post(url, data={}, noEncryption={}) {
        this._readData(url, data, noEncryption);
        let params = this._secretToken(data);
        let datas = Object.assign({}, params, noEncryption);
        axios.defaults.headers = Object.assign({}, this._headers(), {
            'content-type': 'application/x-www-form-urlencoded'
        })
        return axios.post(url, qs.stringify(datas));
    }
    /**
     * post文件上传请求
     * @param {string} url 请求地址
     * @param {string} data 加密字段
     * @param {string} noEncryption 非加密字段
     */
    formDataAjax(url, data={}, noEncryption={}) {
        this._readData(url, data, noEncryption);
        if(!('FormData' in window)) {
            alert('亲，您的浏览器版本太低不支持上传图片，请升级浏览器或换其他主流浏览器');
            return new Promise((resolve, reject) => { resolve(false) });
        }
        axios.defaults.headers = this._headers();
        let params = this._secretToken(data);
        var formData = new FormData();

        for(let i in data) {
            formData.append(i, data[i]);
        }
        formData.append('token', params['token']);
        for(let i in noEncryption) {
            if(Array.isArray(noEncryption[i])) {
                for(let x=0; x<noEncryption[i].length; x++) {
                    formData.append(`${i}[]`, noEncryption[i][x]);
                }
            } else {
                formData.append(i, noEncryption[i]);
            }
            return axios.post(url, formData);
        }
    }
    //请求头部的基础配置
    _headers() {
        return {
            'x-client-id': this.clientId,
            'x-access-user-id': getCookie('userid'),
            'x-access-token': getCookie('accesstoken'),
        }
    }
    //验证传递参数
    _readData(url, data, noEncryption) {
        VariableType.isString(url);
        VariableType.isObj(data);
        VariableType.isObj(noEncryption);
    }
    //加密方式
    _secretToken(data={}) {
        let secret_key = this.secretKey,
            obj = {},
            arr = [],
            token = '';
        
        for(let i in data) {
            arr.push(i)
        }
        arr.sort();
        for(let i=0; i<arr.length; i++) {
            obj[arr[i]] = data[arr[i]];
        }
        for(let i in obj) {
            if(token === '') {
                token = `${token+i}=${obj[i]}`;
            } else {
                token = `${token}&${i}=${obj[i]}`;
            }
        };
        token+=secret_key;
        obj['token'] = md5(token);
        return obj;
    }
}